package Corpus;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Vector;

import DataObjects.Article;
import Main.Pair;
import Main.Threesome;

public class InfomedCorpus implements Corpus{
	
	private class InfomedCorpusIterator implements Iterator<Pair<Article, String>>{
		
		private File[] children;
		private int index;
		
		public InfomedCorpusIterator(){
			children = new File(articlesPath).listFiles();
			index=0;
		}

		public boolean hasNext() {
			return index<children.length;
		}

		private String curntFileToText(){
			String ans="";
			try {
				FileReader reader=new FileReader(children[index]);
				BufferedReader buff=new BufferedReader(reader);
				String line=buff.readLine();
				
				while (line!=null){
					ans+=line+"\n";
					line=buff.readLine();
				}
				
				reader.close();
				buff.close();
				
				return ans;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		private int findFirst(char ch,String text){
			int first=text.indexOf(ch);
			if (first<=0)
				first=text.length()-1;		
			return first;
		}
		
		private String textToTitle(String text){
			char[] chars={',','\'','\n','.','\"',':','(',')','[',']'};
			
			int minIndex=findFirst(chars[0],text);
			
			for(int i=1;i<chars.length;i++){
				int temp=findFirst(chars[i],text);
				if (temp<minIndex)
					minIndex=temp;
			}
			return text.substring(0,minIndex).trim();
		}
		
		public Pair<Article, String> next() {
			String text=curntFileToText();
			Article article=new Article(index, textToTitle(text), text, new Vector<Pair<String,Object>>());
			Pair<Article, String> ans=new Pair<Article, String>(article, children[index].getPath());
			index++;
			return ans;
		}

		public void remove(){}
	}
	

	private String articlesPath;
	
	public InfomedCorpus(String articlesPath){
		this.articlesPath=articlesPath;
	}
	
	public String getAdderssPrefix() {
		return "infomed";
	}

	public Vector<Threesome<String, String, MetadataType>> getAllMetadataNames() {
		return new Vector<Threesome<String, String, MetadataType>>();
	}

	public String getArticlesPath() {
		return articlesPath;
	}

	public Iterator<Pair<Article, String>> getIteratorForTheArticles() {
		return new InfomedCorpusIterator();
	}

	public void init() {
		// TODO Auto-generated method stub	
	}

}
